<template>
  <div class="reset-password">
    <el-form ref="resetForm" :model="resetForm" :rules="resetRules" class="reset-form">
      <h3 class="title">重置密码</h3>
      <p class="subtitle">请输入新密码</p>

      <el-form-item prop="password">
        <el-input
          ref="passwordRef"
          v-model="resetForm.password"
          placeholder="新密码"
          name="password"
          :type="passwordVisible ? 'text' : 'password'"
          autocomplete="new-password">
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          <el-button slot="suffix" type="text" @click="passwordVisible = !passwordVisible">
            <svg-icon :icon-class="passwordVisible ? 'eye-open' : 'eye'" />
          </el-button>
        </el-input>
      </el-form-item>

      <el-form-item prop="confirmPassword">
        <el-input
          v-model="resetForm.confirmPassword"
          placeholder="确认新密码"
          name="confirmPassword"
          :type="confirmPasswordVisible ? 'text' : 'password'"
          autocomplete="new-password">
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          <el-button slot="suffix" type="text" @click="confirmPasswordVisible = !confirmPasswordVisible">
            <svg-icon :icon-class="confirmPasswordVisible ? 'eye-open' : 'eye'" />
          </el-button>
        </el-input>
      </el-form-item>

      <el-form-item style="width: 100%">
        <el-button :loading="loading" size="medium" type="primary" style="width: 100%" @click.native.prevent="handleSubmit">
          <span v-if="!loading">重置密码</span>
          <span v-else>重置中...</span>
        </el-button>
      </el-form-item>

      <div class="back-link">
        <el-link type="primary" @click="goToLogin">返回登录</el-link>
      </div>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <!-- <span>Copyright © 2018-2021 django-vue-admin.com All Rights Reserved.</span> -->
    </div>
  </div>
</template>

<script>
import { resetPassword } from "@/api/vadmin/login";

export default {
  name: "ResetPassword",
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.resetForm.password) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    
    return {
      resetForm: {
        password: "",
        confirmPassword: ""
      },
      resetRules: {
        password: [
          { required: true, trigger: "blur", message: "请输入新密码" },
          { min: 8, message: "密码不能少于8位", trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, trigger: "blur", message: "请确认新密码" },
          { validator: validateConfirmPassword, trigger: "blur" }
        ]
      },
      loading: false,
      passwordVisible: false,
      confirmPasswordVisible: false,
      tokenValid: false,
      token: "",
      username: "",
      email: ""
    };
  },
  created() {
    // 从URL获取token和邮箱参数
    const { token, email } = this.$route.query;
    
    if (!token) {
      this.$notify.error({
        title: "错误",
        message: "无效的密码重置链接，缺少必要参数",
        duration: 5000
      });
      this.goToLogin();
      return;
    }
    
    this.token = token;
    this.email = email;
    // 从邮箱中提取用户名（邮箱@符号前的部分）
    this.username = email ? email.split('@')[0] || '' : '';
    this.tokenValid = true;
  },
  mounted() {
    // 聚焦密码输入框
    this.$nextTick(() => {
      this.$refs.passwordRef && this.$refs.passwordRef.focus();
    });
  },
  methods: {
    handleSubmit() {
      if (!this.tokenValid) {
        this.$notify.error({
          title: "错误",
          message: "密码重置链接已过期或无效",
          duration: 5000
        });
        return;
      }
      
      this.$refs.resetForm.validate(valid => {
        if (valid) {
          this.loading = true;
          // 构造重置密码请求参数
          const resetData = {
            username: this.username, // 已从email中提取的用户名
            email: this.email,
            token: this.token,
            new_password: this.resetForm.password,
            confirm_password: this.resetForm.confirmPassword
          };
          
          resetPassword(resetData)
            .then(() => {
              this.$notify({
                title: "成功",
                message: "密码重置成功，请使用新密码登录",
                type: "success",
                duration: 5000
              });
              setTimeout(() => {
                this.goToLogin();
              }, 2000);
            })
            .catch(error => {
              console.error(error);
              this.$notify.error({
                title: "错误",
                message: "密码重置失败，请重试或获取新的重置链接",
                duration: 5000
              });
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    goToLogin() {
      this.$router.push("/login");
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.reset-password {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}

.title {
  margin: 0px auto 20px auto;
  text-align: center;
  color: #707070;
}

.subtitle {
  font-size: 14px;
  color: #606266;
  text-align: center;
  margin-bottom: 25px;
  line-height: 1.5;
}

.reset-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
  
  .back-link {
    text-align: center;
    margin: 15px 0;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
</style> 